package com.tvunetworks.center.device.util;

import com.tvunetworks.center.device.model.router.Client;
import com.tvunetworks.center.device.model.router.Connection;
import com.tvunetworks.center.device.model.router.Peer;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @program: tvucc-aggregator
 * @author Kevin_Li
 * @create: 2020-01-08 12:06
 **/
public class XmlToPeer {
    /**
     * xml to Peer
     * @param xml  xml
     * @return List
     * @throws Exception 編譯异常
     */
    public static List<Peer> xmlToPeer(String xml) throws Exception {
        StringReader sr = new StringReader(xml);
        InputSource is = new InputSource(sr);
        SAXReader reader = new SAXReader();
        Document document = reader.read(is);
        //get root Node
        Element root = document.getRootElement();
        //get peers Node
        Element peers = root.element("peers");
      //  Element statistics = root.element("statistics");
        //get peer Node
        List peerList = peers.elements("peer");
        //Iterator  peerList
        List<Peer> peerLists = new ArrayList<Peer>();
        for (Iterator it = peerList.iterator(); it.hasNext(); ) {
            Peer pr = new Peer();
            Element peer = (Element) it.next();
            //get peer Attributes
            for(Iterator ip = peer.attributeIterator();ip.hasNext();){
                Attribute peerAttribute = (Attribute) ip.next();
                String name = peerAttribute.getName();
                String value = peerAttribute.getValue();
                if(name.equals("peerId")){
                    pr.setPeerId(value);
                }else if("connected".equals(name)){
                    pr.setConnected(value);
                }else if("connectedTimeInSeconds".equals(name)){
                    pr.setConnectedTimeInSeconds(value);
                }else if("receivedSourcePacketsNum".equals(name)){
                    pr.setReceivedSourcePacketsNum(value);
                }else if("receivedRepairPacketsNum".equals(name)){
                    pr.setReceivedRepairPacketsNum(value);
                }else if("receivedBytesInSession".equals(name)){
                    pr.setReceivedBytesInSession(value);
                }else if("sentBytesInSession".equals(name)){
                    pr.setSentBytesInSession(value);
                }else if("receivedBitsPerSecond".equals(name)){
                    pr.setReceivedBitsPerSecond(value);
                }else if("sentBitsPerSecond".equals(name)){
                    pr.setSentBitsPerSecond(value);
                }
            }
            //get connections Node
            Element connections = peer.element("connections");
            //get Connection list
            List<Connection> listCon = iteratorConnection(connections, "connection");
            pr.setConnectionList(listCon);
            //get clients Node
            Element clients = peer.element("clients");
            if(clients !=null){
                //get Client list
                List<Client> listClt = iteratorClient(clients, "client");
                pr.setClientList(listClt);
            }
//            for (Iterator ip = statistics.attributeIterator();ip.hasNext();){
//                Attribute statisticsAttribute = (Attribute) ip.next();
//                String name = statisticsAttribute.getName();
//                String value = statisticsAttribute.getValue();
//                if(name.equals("receivedBitsPerSecond")){
//                    pr.setReceivedBitsPerSecond(value);
//                }else if(name.equals("receivedBytesPerSecond")){
//                    pr.setReceivedBytesPerSecond(value);
//                }else if(name.equals("receivedPacketsPerSecond")){
//                    pr.setReceivedPacketsPerSecond(value);
//                }else if(name.equals("sentBitsPerSecond")){
//                    pr.setSentBitsPerSecond(value);
//                }else if(name.equals("sentBytesPerSecond")){
//                    pr.setSentBytesPerSecond(value);
//                }else if(name.equals("sentPacketsPerSecond")){
//                    pr.setSentPacketsPerSecond(value);
//                }
//            }
            peerLists.add(pr);

        }
        return peerLists;
    }

    private static List<Connection> iteratorConnection(Element connections, String connectionName) {
        List<Connection> list = new ArrayList<Connection>();
        List connectionList = connections.elements(connectionName);
        //Iterator connectionList
        for (Iterator i = connectionList.iterator(); i.hasNext(); ) {
            Element connection = (Element) i.next();
            Connection con = new Connection();
            for (Iterator ic = connection.attributeIterator(); ic.hasNext(); ) {
                Attribute connectionAttribute = (Attribute) ic.next();
                String name = connectionAttribute.getName();
                String value = connectionAttribute.getValue();
                if (name.equals("connected")) {
                    con.setConnected(value);
                } else if (name.equals("localSlotId")) {
                    con.setLocalSlotId(value);
                } else if (name.equals("remoteSlotId")) {
                    con.setRemoteSlotId(value);
                } else if (name.equals("localAddress")) {
                    con.setLocalAddress(value);
                } else if (name.equals("remoteAddress")) {
                    con.setRemoteAddress(value);
                } else if (name.equals("receivedBitsPerSecond")) {
                    con.setReceivedBitsPerSecond(value);
                } else if (name.equals("sentBitsPerSecond")) {
                    con.setSentBitsPerSecond(value);
                } else if (name.equals("receivedBytesInSession")) {
                    con.setReceivedBytesInSession(value);
                } else if (name.equals("sentBytesInSession")) {
                    con.setSentBytesInSession(value);
                } else if (name.equals("isWeak")) {
                    con.setIsWeak(value);
                } else if (name.equals("rttInMsec")) {
                    con.setRttInMsec(value);
                }
            }
            list.add(con);
        }
        return list;
    }

    private static List<Client> iteratorClient(Element clients, String clientName) {
        List clientList = clients.elements(clientName);
        List<Client> list = new ArrayList<Client>();
        //Iterator clientList
        for (Iterator j = clientList.iterator(); j.hasNext(); ) {
            Element client = (Element) j.next();
            Client clt = new Client();
            for (Iterator ic = client.attributeIterator(); ic.hasNext(); ) {
                Attribute clientAttribute = (Attribute) ic.next();
                String name = clientAttribute.getName();
                String value = clientAttribute.getValue();
                if (name.equals("macAddress")) {
                    clt.setMacAddress(value);
                } else if (name.equals("realIpAddress")) {
                    clt.setRealIpAddress(value);
                } else if (name.equals("name")) {
                    clt.setName(value);
                }
            }
            list.add(clt);
        }
        return list;
    }

    /**
     * json to Peer
     * @param args args

     */

    public static void main(String  [] args){
//        String json = "{\n" +
//                " \"status\": {\n" +
//                "  \"connected\": \"yes\",\n" +
//                "  \"localPeerId\": \"0x1122334455667788\",\n" +
//                "  \"bestPeerId\": \"0x7B8C16FE88A07008\",\n" +
//                "  \"connectedPeersNum\": \"1\",\n" +
//                "  \"connectedPeers\": {\n" +
//                "   \"connectedPeer\": [{\n" +
//                "    \"peerId\": \"0x7B8C16FE88A07008\"\n" +
//                "   }]\n" +
//                "  },\n" +
//                "  \"statistics\": {\n" +
//                "   \"receivedBitsPerSecond\": \"0\",\n" +
//                "   \"receivedBytesPerSecond\": \"0\",\n" +
//                "   \"receivedPacketsPerSecond\": \"0\",\n" +
//                "   \"sentBitsPerSecond\": \"0\",\n" +
//                "   \"sentBytesPerSecond\": \"0\",\n" +
//                "   \"sentPacketsPerSecond\": \"0\",\n" +
//                "   \"receivedBytesSinceStart\": \"227\",\n" +
//                "   \"receivedPacketsSinceStart\": \"6\",\n" +
//                "   \"sentBytesSinceStart\": \"133\",\n" +
//                "   \"sentPacketsSinceStart\": \"4\",\n" +
//                "   \"runningTimeInSeconds\": \"37\"\n" +
//                "  },\n" +
//                "  \"peers\": {\n" +
//                "   \"peer\": [{\n" +
//                "    \"peerId\": \"0x7B8C16FE88A07008\",\n" +
//                "    \"connected\": \"yes\",\n" +
//                "    \"connectedTimeInSeconds\": \"16\",\n" +
//                "    \"receivedSourcePacketsNum\": \"2\",\n" +
//                "    \"receivedRepairPacketsNum\": \"0\",\n" +
//                "    \"receivedBitsPerSecond\": \"0\",\n" +
//                "    \"sentBitsPerSecond\": \"0\",\n" +
//                "    \"receivedBytesInSession\": \"114\",\n" +
//                "    \"sentBytesInSession\": \"66\",\n" +
//                "    \"connections\": {\n" +
//                "     \"connection\": [{\n" +
//                "      \"connected\": \"yes\",\n" +
//                "      \"localSlotId\": \"1\",\n" +
//                "      \"remoteSlotId\": \"13\",\n" +
//                "      \"localAddress\": \"0.0.0.0:6532\",\n" +
//                "      \"remoteAddress\": \"10.10.20.99:23693\",\n" +
//                "      \"receivedBitsPerSecond\": \"0\",\n" +
//                "      \"sentBitsPerSecond\": \"0\",\n" +
//                "      \"receivedBytesInSession\": \"114\",\n" +
//                "      \"sentBytesInSession\": \"66\",\n" +
//                "      \"isWeak\": \"no\",\n" +
//                "      \"rttInMsec\": \"0\"\n" +
//                "     }]\n" +
//                "    }\n" +
//                "   }]\n" +
//                "  }\n" +
//                " }\n" +
//                "}";
//        //Fixme 删除测试数据
//        List<Peer> peerList = new ArrayList<Peer>();
//        JSONObject jsonstatus = JSONObject.fromObject(json);
//        String statusJson = jsonstatus.get("status").toString();
//        JSONObject jsonObject = JSONObject.fromObject(statusJson);
//        String peerJson = jsonObject.get("peers").toString();
//        System.out.println(statusJson);
//        try {
//            String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
//                    "<Root>\n" +
//                    "      <Version>1.0</Version >\n" +
//                    "     <Appkey>bd25b9efb773ab73957ea60155951229</Appkey>\n" +
//                    "     <Timestamp>1451498400000</Timestamp>\n" +
//                    "     <Signature>97db51ef63d627e2251183a9d9d02ddb</Signature>\n" +
//                    "     <Session>D5E211C81036F434584231E1E2C56725</Session>\n" +
//                    "</Root>\n";
//            StringReader sr = new StringReader(xml);
//            InputSource is = new InputSource(sr);
//            SAXReader reader = new SAXReader();
//            Document document = reader.read(is);
//            //get root Node
//            Element root = document.getRootElement();
//            //get peers Node
//            Element peers = root.element("Version");
//           String aa =  peers.getName();
//            String ab = peers.getStringValue();
//        } catch (DocumentException e) {
//            log.error("msg:{},e:{}",e.getMessage(),e);
//        }
        String mysignature = StringUtil.MD5("f376af8addc5e3a566545cf3ed36f197"+"1451498400000");
        System.out.println(mysignature);
        //get peer Node
//
    }

}
